#include <iostream>
#include <unistd.h>
#include <pthread.h>
using namespace std;
#define NUM 5

enum class Status
{
    OK = 0,
    ERROR
};

class ThreadData
{
public:
    ThreadData(const string &name, int id, int n)
        :_name(name)
        ,_id(id)
        ,_createTime(time(nullptr))
        ,_n(n)
        ,_result(0)
        ,_status(Status::OK)
    {}

public:
    string _name;
    int _id;
    time_t _createTime;
    int _n;
    int _result;
    Status _status;
};

void* threadRun(void *arg)
{
    ThreadData *td = static_cast<ThreadData*>(arg);
    for(int i = 0; i <= td->_n; i++)
    {
        td->_result += i;
    }

    cout << "线程" << td->_name << "ID: " << td->_id << "CreateTime: " << td->_createTime << "done..." << endl;
    pthread_exit((void*)td);
}

int main()
{
    pthread_t pt[NUM];

    for(int i = 0; i < NUM; i++)
    {
        // 注册新线程的信息
        char name[64];
        snprintf(name, sizeof(name), "thread-%d", i + 1);

        // 创建对象
        ThreadData *td = new ThreadData(name, i, 100 * (10 + i));
        pthread_create(pt + i, nullptr, threadRun, td);
        sleep(1); // 尽量拉开创建时间
    }

    // 等待次线程运行结束
    void *retval = nullptr;
    for(int i = 0; i < NUM; i++)
    {
        int ret = pthread_join(pt[i], &retval);
        if(ret != 0)
            cerr << "等待线程 " << pt[i] << " 失败!" << endl;

        ThreadData *td = static_cast<ThreadData*>(retval);

        if(td->_status == Status::OK)
            cout << "线程 " << pt[i] << " 计算 [0, " << td->_n << "] 的累加和结果为 " << td->_result << endl;
        delete td;
    }

    cout << "所有线程都退出了" << endl;

    return 0;
}

